package c.main.core;

import c.main.jdbc.JdbcTemplate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.rmi.MarshalledObject;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: chengwei
 * Date:   2016/3/16
 * Time:   13:38
 */
public class HttpView {
    private HttpServletRequest request;
    private HttpServletResponse response;

    public HttpView(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }
    
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public HttpSession getSession() {
        return request.getSession(false);
    }
    
    public void forwardJsp(String url) throws ServletException, IOException {
        request.getRequestDispatcher(String.format("/WEB-INF/jsp/%s.jsp",url)).forward(request,response);
    }

    public void forwardUrl(String url) throws ServletException, IOException {
        request.getRequestDispatcher(url).forward(request,response);
    }

    public void sendRedirect(String url) throws ServletException, IOException {
        response.sendRedirect(url);
    }
    
    
    public String getParameter(String s) {
        return request.getParameter(s);
    }

    public Map<String,String> getParameters() {
        Map<String,String> params = new HashMap<>();
        Map<String,String[]> map = request.getParameterMap();
        String[] values;
        String value ;
        for(String key : map.keySet()) {
            values = map.get(key);
            value = "";
            for (int i = 0; i< values.length ;i++) {
                if (i > 0) {
                    value += ",";
                }
                value += values[i];
            }
            params.put(key,value);
        } 
        return params;
    }
}
